package com.sky.service.user.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.lang.UUID;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.OrdersPageQueryDTO;
import com.sky.dto.OrdersPaymentDTO;
import com.sky.dto.OrdersSubmitDTO;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.admin.DishMapper;
import com.sky.mapper.admin.SetmealMapper;
import com.sky.mapper.user.*;
import com.sky.pojo.*;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.user.OrderService;
import com.sky.utils.SignUtils;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 订单
 */
@Service
@Slf4j
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private SetmealMapper setmealMapper;
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private WeChatPayUtil weChatPayUtil;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private SignUtils signUtils;
    /**
     * 用户下单
     *
     * @param ordersSubmitDTO
     * @return
     */
    @Override
    @Transactional
    public OrderSubmitVO submitOrder(OrdersSubmitDTO ordersSubmitDTO) {
        //异常情况的处理（收货地址为空、超出配送范围、购物车为空）
        AddressBook addressBook = addressBookMapper.selectById(ordersSubmitDTO.getAddressBookId());
        if (addressBook == null) {
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }

        Long userId = BaseContext.getCurrentId();
        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setUserId(userId);

        //查询当前用户的购物车数据
        List<ShoppingCart> shoppingCartList = shoppingCartMapper.selectAll(shoppingCart);
        if (shoppingCartList == null || shoppingCartList.size() == 0) {
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }

        //构造订单数据
        Orders order = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO,order);
        order.setPhone(addressBook.getPhone());
        order.setAddress(addressBook.getProvinceName()+addressBook.getCityName()+addressBook.getDistrictName()+addressBook.getDetail());

        order.setConsignee(addressBook.getConsignee());
        order.setNumber(UUID.randomUUID().toString().replaceAll("-",""));
        order.setUserId(userId);
        order.setStatus(Orders.PENDING_PAYMENT);
        order.setPayStatus(Orders.UN_PAID);
        order.setOrderTime(LocalDateTime.now());

        //预计送达时间
        order.setDeliveryTime(ordersSubmitDTO.getEstimatedDeliveryTime());
        //出餐时间
        Integer makeTime = 0;
        for (ShoppingCart cart : shoppingCartList) {
            if(cart.getSetmealId()!=null){
                SetmealVO setmealVO = setmealMapper.selectById(cart.getSetmealId());
                makeTime += setmealVO.getMakeTime();
            }
            DishVO dishVO = dishMapper.selectById(cart.getDishId());
            makeTime += dishVO.getMakeTime();
        }
        order.setMealTime(LocalDateTime.now().plusMinutes(makeTime));

        //向订单表插入1条数据
        orderMapper.insert(order);

        //订单明细数据
        List<OrderDetail> orderDetailList = new ArrayList<>();
        for (ShoppingCart cart : shoppingCartList) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart, orderDetail);
            orderDetail.setOrderId(order.getId());
            orderDetailList.add(orderDetail);
        }

        //向明细表插入n条数据
        orderDetailMapper.insertBatch(orderDetailList);

        //清理购物车中的数据
        shoppingCartMapper.deleteByUserId(userId);

        //封装返回结果
        OrderSubmitVO orderSubmitVO = OrderSubmitVO.builder()
                .id(order.getId())
                .orderNumber(order.getNumber())
                .orderAmount(order.getAmount())
                .orderTime(order.getOrderTime())
                .build();

        return orderSubmitVO;
    }

    /**
     * 支付
     * @param dto
     * @return
     */
    @Override
    public Result<OrderPaymentVO> payment(OrdersPaymentDTO dto)  {
        String resStr = null;
        //获取用户信息
        User user = userMapper.selectById(BaseContext.getCurrentId());
        try {


        //下单  -- 封装好的api
        BigDecimal bigDecimal = BigDecimal.valueOf(1);
        String jsonStr = weChatPayUtil.wxnative(dto.getOrderNumber(), bigDecimal, "苍穹外卖订单");
        Map map = JSON.parseObject(jsonStr, Map.class);
        //解析参数
        String packageStr = "prepay_id="+map.get("prepay_id").toString();

        //签名加密 -- 包含了OrderPaymentVo的所有信息，直接json解析对象即可
         resStr = signUtils.sign(packageStr.getBytes());
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }

        OrderPaymentVO vo = JSON.parseObject(resStr, OrderPaymentVO.class);

        return Result.success(vo);
    }

    /**
     * 获取用户期望送达时间
     * @return
     */
    @Override
    public String getEstimatedDeliveryTime() {
        String format="";
        LocalDateTime orderTime = LocalDateTime.of(2000,01,01,0,0,0);
        //根据用户id和下单时间查询预期送达时间
        Long userId = BaseContext.getCurrentId();
        List<Orders> ordersList = orderMapper.selectByUserId(userId);
        for (Orders orders : ordersList) {
            if(orderTime.isBefore(orders.getOrderTime())){
                orderTime = orders.getOrderTime();
            }
        }
        LocalDateTime estimatedDeliveryTime = orderMapper.getEstimatedDeliveryTime(userId,orderTime);
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        if(estimatedDeliveryTime != null){
             format = estimatedDeliveryTime.format(formatter);
        }
        return format;
    }

    /**
     * 历史订单分页查询
     * @param page
     * @param pageSize
     * @param status
     * @return
     */
    @Override
    public PageResult getHistoryOrders(Integer page, Integer pageSize, Integer status) {
        // 设置分页
        PageHelper.startPage(page, pageSize);

        OrdersPageQueryDTO ordersPageQueryDTO = new OrdersPageQueryDTO();
        ordersPageQueryDTO.setUserId(BaseContext.getCurrentId());
        ordersPageQueryDTO.setStatus(status);

        // 分页条件查询
        Page<Orders> pageQuery = orderMapper.pageQuery(ordersPageQueryDTO);

        List<OrderVO> list = new ArrayList();

        // 查询出订单明细，并封装入OrderVO进行响应
        if (page != null && pageQuery.getTotal() > 0) {
            for (Orders orders : pageQuery) {
                Long orderId = orders.getId();// 订单id

                // 查询订单明细
                List<OrderDetail> orderDetails = orderDetailMapper.getByOrderId(orderId);

                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(orders, orderVO);
                orderVO.setOrderDetailList(orderDetails);

                list.add(orderVO);
            }
        }
        return new PageResult(pageQuery.getTotal(), list);
    }
}
